<script setup lang="ts">
import { onMounted, reactive, ref } from "vue";
import ScreenTable from "@/components/ScreenTable/index.vue";
import { ITableData, IQueryParams, ITableListItem } from "./data";
import { IResponseData } from "@/@types/utils.request";
import { queryList, update, save, removeData } from "./service";
import { ElMessage } from "element-plus";
import { ResultCodeEnum } from "@/enums/utils.request.enum";
import { useUserStore } from "@/store/user";
/* ====================== 表格 - 获取数据 S ============== */
// 表格 - 列表 - 初始化数据
const tableData = reactive<ITableData>({
	loading: false,
	list: [],
	pagination: {
		total: 0,
		current: 1,
		pageSize: 20,
		sizeChange: () => {},
		onChange: () => {},
	},
});

const userStore = useUserStore();
const searchKey = reactive<IQueryParams>({
	floorId: undefined,
	buildingId: undefined,
	ownersId: undefined,
});

if (userStore.roles.includes("owners")) {
	searchKey.ownersId = userStore.id;
}

// 表格 - index
const tableIndexMethod = (index: number) => {
	return index + (tableData.pagination.current - 1) * tableData.pagination.pageSize + 1;
};

const getList = async (key: IQueryParams): Promise<void> => {
	tableData.loading = true;
	try {
		const response: IResponseData<any> = await queryList({
			pageSize: tableData.pagination.pageSize,
			pageNum: tableData.pagination.current,
			data: key,
		});
		const { data, total } = response;
		tableData.list = data || [];
		tableData.pagination = {
			total: Number(total) || 0,
			current: tableData.pagination.current,
			pageSize: tableData.pagination.pageSize,
			sizeChange: (size) => {
				tableData.pagination.current = size;
				getList(key);
			},
			onChange: (size) => {
				tableData.pagination.current = size;
				getList(key);
			},
		};
	} catch (error: any) {
		console.log(error);
	}
	tableData.loading = false;
};
onMounted(() => {
	getList(searchKey);
});

const dialogUpdateVisible = ref(false);
const dialogAddVisible = ref(false);

const saveData = reactive<ITableListItem>({
	roomNumber: -1,
	floorId: -1,
	releaseTime: "",
	ownerId: -1,
});
const updateData = reactive<ITableListItem>({
	roomId: -1,
	roomNumber: -1,
	floorId: -1,
	releaseTime: "",
	ownerId: -1,
});

const saveSub = async (data?: ITableListItem) => {
	if (!data) {
		ElMessage.error("信息错误");
		return;
	}
	const response: IResponseData<ITableListItem> = await save(data);
	const { code } = response;
	if (code == ResultCodeEnum.SUCCESS) {
		ElMessage.success("保存成功");
		dialogAddVisible.value = false;
		saveData.roomNumber = -1;
		saveData.floorId = -1;
		saveData.releaseTime = "";
		saveData.ownerId = -1;
		getList(searchKey);
	} else {
		ElMessage.error(response.message);
	}
};

const showDetail = (data: ITableListItem) => {
	updateData.roomId = data.roomId;
	updateData.roomNumber = data.roomNumber;
	updateData.floorId = data.floorId;
	updateData.releaseTime = getReleaseTime(data.releaseTime);
	updateData.ownerId = data.ownerId;
	dialogUpdateVisible.value = true;
};

const getReleaseTime = (time: string) => {
	const date = new Date(time);
	var year = date.getFullYear();
	var month = date.getMonth() + 1; // 月份是从0开始的，所以加1
	var day = date.getDate();
	var hour = date.getHours();
	var minute = date.getMinutes();
	var second = date.getSeconds();
	console.log(year, month, day, hour, minute, second);
	return `${year}-${month < 10 ? "0" + month : month}-${day < 10 ? "0" + day : day} ${hour < 10 ? "0" + hour : hour}:${
		minute < 10 ? "0" + minute : minute
	}:${second < 10 ? "0" + second : second}`;
};

const updateSub = async (data?: ITableListItem) => {
	if (!data) {
		ElMessage.error("信息错误");
		return;
	}
	const response: IResponseData<ITableListItem> = await update(data);
	const { code } = response;
	if (code == ResultCodeEnum.SUCCESS) {
		ElMessage.success("保存成功");
		dialogUpdateVisible.value = false;
		getList(searchKey);
	} else {
		ElMessage.error(response.message);
	}
};
const removeUser = async (id: number) => {
	// TODO
	const response: IResponseData<ITableListItem> = await removeData(id);
	const { code } = response;
	if (code == ResultCodeEnum.SUCCESS) {
		ElMessage.success("删除成功");
		getList(searchKey);
	} else {
		ElMessage.error(response.message);
	}
};
</script>
<template>
  <ScreenTable row-key="id" :data="tableData.list" :loading="tableData.loading" :pagination="tableData.pagination">

    <template #header>
      <div class="header-box">
        <div class="header-box__left">
          <el-input placeholder="请输入楼层ID" v-model="searchKey.floorId" style="width: 180px;margin-left: 10px;" />

          <el-input v-if="userStore.roles.includes('admin')" placeholder="请输入业主ID" v-model="searchKey.ownersId" style="width: 180px;margin-left: 10px;" />

          <el-button type="primary" @click="getList(searchKey)">搜索</el-button>
        </div>
        <el-button v-if="userStore.roles.includes('admin')" type="primary" @click="dialogAddVisible = true">新增</el-button>
      </div>
    </template>

    <el-table-column fixed label="序号" type="index" :index="tableIndexMethod" width="80"> </el-table-column>
    <el-table-column label="房间号" prop="roomNumber" width="150"> </el-table-column>
    <el-table-column label="楼层号ID" prop="floorId" width="100"> </el-table-column>
    <el-table-column label="业主ID" prop="ownerId" width="100"> </el-table-column>
    <el-table-column label="发布时间" prop="releaseTime">
      <template #default="scope">{{
				getReleaseTime(scope.row.releaseTime)
				}}</template>

    </el-table-column>
    <el-table-column v-if="userStore.roles.includes('admin')" label="操作" prop="action" width="150" fixed="right">
      <template #default="scop">
        <el-button type="primary" link @click="showDetail(scop.row)">编辑</el-button>
        <el-button type="danger" link @click="removeUser(scop.row.roomId)">删除</el-button>
      </template>
    </el-table-column>
  </ScreenTable>

  <!-- 修改 -->
  <el-dialog v-model="dialogUpdateVisible" top="20vh" title="修改信息">
    <el-form :model="updateData" label-width="auto" style="max-width: 600px">
      <el-form-item label="房间ID" style="display: none;">
        <el-input v-model="updateData.roomId" />
      </el-form-item>
      <el-form-item label="房间号">
        <el-input v-model="updateData.roomNumber" />
      </el-form-item>
      <el-form-item label="楼层号">
        <el-input v-model="updateData.floorId" />
      </el-form-item>
      <el-form-item label="业主ID">
        <el-input v-model="updateData.ownerId" />
      </el-form-item>
      <el-form-item label="发布时间">
        <el-date-picker v-model="updateData.releaseTime" type="datetime" placeholder="选择发布时间" format="YYYY-MM-DD hh:mm:ss" value-format="YYYY-MM-DD hh:mm:ss" />
      </el-form-item>
      <el-button type="primary" @click="updateSub(updateData)">提交</el-button>
    </el-form>
  </el-dialog>

  <!-- 添加 -->
  <el-dialog v-model="dialogAddVisible" top="20vh" title="添加房间">
    <el-form :model="updateData" label-width="auto" style="max-width: 600px">
      <el-form-item label="房间ID" style="display: none;">
        <el-input v-model="saveData.roomId" />
      </el-form-item>
      <el-form-item label="房间号">
        <el-input v-model="saveData.roomNumber" />
      </el-form-item>
      <el-form-item label="楼层号">
        <el-input v-model="saveData.floorId" />
      </el-form-item>
      <el-form-item label="业主ID">
        <el-input v-model="saveData.ownerId" />
      </el-form-item>
      <el-form-item label="发布时间">
        <el-date-picker v-model="saveData.releaseTime" type="datetime" placeholder="选择发布时间" format="YYYY-MM-DD hh:mm:ss" value-format="YYYY-MM-DD hh:mm:ss" />
      </el-form-item>
      <el-button type="primary" @click="saveSub(saveData)">提交</el-button>
    </el-form>
  </el-dialog>
</template>
